<template>
  <el-dialog width="80%" :title="dialogTitle" v-model="dialogVisible" modal @close="closeDialog" draggable
    :close-on-click-modal="false" :append-to-body="true">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" height="50vh" style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"> </el-table-column>
          <el-table-column type="index" width="50" label="序号" align="cneter"> </el-table-column>
          <el-table-column v-for="item of tableProps" :key="item.props" :prop="item.prop" :label="item.title"
            :min-width="item.width">
            <template slot-scope="{ row }">
              <div v-if="item.prop === 'fieldType'">
                <el-tag size="small" v-if="row.fieldType == 0">业务字段</el-tag>
                <el-tag size="small" v-else-if="row.fieldType == 1">内置字段</el-tag>
                <el-tag size="small" v-else>自定义字段</el-tag>
              </div>
              <div v-else-if="item.prop === 'dataType'">
                <el-tag size="small" type="info">{{ row.dataType }}</el-tag>
              </div>
              <div v-else>{{ row[item.prop] }}</div>
            </template>
          </el-table-column>
        </el-table>
        <div class="margin10Top">
          <el-button size="mini" @click="addToRight" type="primary">添加到到右侧</el-button>
        </div>
      </el-col>
      <el-col :span="12">
        <el-table ref="multipleTable" :data="backUpTableData" tooltip-effect="dark" height="50vh" style="width: 100%"
          @selection-change="handleSelectionChangeBackUp">
          <el-table-column type="selection" width="55" align="center"> </el-table-column>
          <el-table-column type="index" width="50" label="序号" align="cneter"> </el-table-column>
          <el-table-column v-for="item of tablePropsAdd" :key="item.props" :prop="item.prop" :label="item.title"
            :min-width="item.width">
            <template slot-scope="{ row }">
              <div v-if="item.prop === 'newFieldTitle'">
                <el-input v-model="row.newFieldTitle" size="mini"></el-input>
              </div>
              <div v-else-if="item.prop === 'fieldType'">
                <el-tag size="small" v-if="row.fieldType == 0">业务字段</el-tag>
                <el-tag size="small" v-else-if="row.fieldType == 1">内置字段</el-tag>
                <el-tag size="small" v-else>自定义字段</el-tag>
              </div>
              <div v-else-if="item.prop === 'dataType'">
                <el-tag size="small" type="info">{{ row.dataType }}</el-tag>
              </div>
              <div v-else>{{ row[item.prop] }}</div>
            </template>
          </el-table-column>
        </el-table>
        <div class="flex justify-between margin10Top">
          <el-button @click="deleteAll" type="danger" size="mini">批量删除</el-button>
          <el-button type="primary" @click="submitForm" size="mini">保存</el-button>
        </div>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
// import { EventBus } from '@/utils/EventBus'
import { busMetadataList, resetArchiveFields, resetBoxFields } from '@/api/sys/field'

export default {
  name: 'CustomDialog',
  props: {
    parentTableData: {
      type: Array,
      default: () => {
        return []
      },
    },
    activeFlag: {
      type: String,
      default: '0',
    },
  },

  data() {
    return {
      type: '',
      dialogTitle: '',
      dialogVisible: false,
      activeName: '0',
      tableData: [],
      backUpTableData: [],
      itemLeft: [],
      itemRight: [],
      tableProps: [
        { title: '字段标题', prop: 'fieldTitle', width: '', checked: true },
        { title: '数据库字段', prop: 'fieldName', width: '100', checked: true },
        { title: '数据类型', prop: 'dataType', width: '', checked: true },
        { title: '数据长度', prop: 'dataLength', width: '', checked: true },
        { title: '字段类型', prop: 'fieldType', width: '', checked: true },
      ],
      tablePropsAdd: [
        { title: '字段标题', prop: 'newFieldTitle', width: '150', checked: true },
        { title: '原始字段标题', prop: 'fieldTitle', width: '120', checked: true },
        { title: '数据库字段', prop: 'fieldName', width: '120', checked: true },
        { title: '数据类型', prop: 'dataType', width: '', checked: true },
        { title: '字段类型', prop: 'fieldType', width: '', checked: true },
      ],
    }
  },
  watch: {
    parentTableData(nevw) {
      alert('123')
      // 对数据进行拷贝，重点：防止子组价修改数据影响父组件
      const newData = nevw.map((x) => {
        x.newFieldTitle = x.fieldTitle
        return x
      })
      this.backUpTableData = JSON.parse(JSON.stringify(newData))
      setTimeout(() => {
        if (this.tableData.length > 0) {
          // 获取到数据之后与backUpTableData中的fieldName进行对比,如果一样就去除掉，并且将 fieldTitle 赋值给 newFieldTitle
          // 去除掉与tableData中fieldName一样的数据
          this.tableData = this.tableData.filter(
            (item) => !this.backUpTableData.some((item1) => item1.fieldName === item.fieldName)
          )
        }
      }, 500)
    },
    activeFlag(nevw) {
      this.activeName = nevw
      this.getbusMetadataList()
    },
  },
  created() {
    // 放到这里，防止数据还没有加载完成就渲染了.父子组件的加载顺序,勿动
    this.getbusMetadataList()
    this.reRender()
  },
  mounted() {
    // EventBus.$on('aMsg', (row) => {
    //   // A发送来的消息
    //   this.edit(row)
    // })
  },
  methods: {
    // 重新渲染
    reRender() {
      // 对数据进行拷贝，重点：防止子组价修改数据影响父组件
      const newData = this.parentTableData.map((x) => {
        x.newFieldTitle = x.fieldTitle
        return x
      })
      this.backUpTableData = JSON.parse(JSON.stringify(newData))
      setTimeout(() => {
        if (this.tableData.length > 0) {
          // 获取到数据之后与backUpTableData中的fieldName进行对比,如果一样就去除掉，并且将 fieldTitle 赋值给 newFieldTitle
          // 去除掉与tableData中fieldName一样的数据
          this.tableData = this.tableData.filter(
            (item) => !this.backUpTableData.some((item1) => item1.fieldName === item.fieldName)
          )
        }
      }, 500)
    },

    // 批量删除
    deleteAll() {
      // 判断this.itemRight中是否有fieldType==0的，如果存在，则不能删除
      if (this.itemRight.some((item) => item.fieldType == 1 || item.fieldType == 0)) {
        this.$confirm('内置字段或业务字段建议不要删除，删除可能导致系统异常, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.delete()
        })
        return
      }
      this.delete()
    },
    delete() {
      // this.itemRight选择的值删除将在backUpTableData中删除
      this.itemRight.map((item) => {
        for (let j = 0; j < this.backUpTableData.length; j++) {
          if (item === this.backUpTableData[j]) {
            this.backUpTableData.splice(j, 1)
          }
        }
        this.tableData.push(item)
      })
    },

    // 添加到右侧
    addToRight() {
      // 将this.itemLeft选择的值添加到backUpTableData,并且这个this.tableData中去掉
      this.itemLeft.map((item) => {
        this.backUpTableData.push({
          ...item,
          newFieldTitle: item.fieldTitle,
        })
        for (let j = 0; j < this.tableData.length; j++) {
          if (item === this.tableData[j]) {
            this.tableData.splice(j, 1)
          }
        }
      })
    },
    handleSelectionChange(item) {
      this.itemLeft = item
    },
    handleSelectionChangeBackUp(item) {
      this.itemRight = item
    },
    // 获取全部的字段
    getbusMetadataList() {
      busMetadataList().then((res) => {
        if (res.data.code === 200) {
          this.tableData = res.data.data
        }
      })
    },
    add(type) {
      this.type = 'add'
      if (type === '0') {
        this.dialogTitle = '档案字段维护'
      } else if (type === '1') {
        this.dialogTitle = '盒字段维护'
      }
      this.dialogVisible = true
    },
    edit(row) {
      this.dialogVisible = true
      this.type = 'edit'
      this.dialogTitle = '编辑字段'
      // getInfo(row.accountId).then(res => {
      //   if (res.data.code === 200) {
      //     this.formData = res.data.data;
      //     this.formData.sex = this.formData.sex.toString();
      //     if (this.formData.selectedroles) {
      //       this.formData.selectedroles = this.formData.selectedroles.split(',');
      //     }
      //     this.dialogVisible = true
      //   } else {
      //     this.$message.error(res.data.message);
      //   }
      // }).catch(err => {
      //   this.$message.error(err);
      // })
    },
    // 确定提交
    submitForm() {
      // this.backUpTableDat 将数组中的newFieldTitle的值赋值给fieldTitle
      // 后端需要接收的值是fieldTitle
      const params = this.backUpTableData.map((item) => {
        item.fieldTitle = item.newFieldTitle
        return item
      })
      var url
      if (this.activeFlag == '1') {
        url = resetBoxFields(params)
      } else {
        url = resetArchiveFields(params)
      }
      url
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.dialogVisible = false
            this.$emit('uplist', this.activeFlag)
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    closeDialog() {
      this.dialogVisible = false
      this.$emit('destroyed')
    },
  },
}
</script>

<style scoped>
.dialog-form {
  padding: 0 30px;
  /* 根据需求调整数值 */
}
</style>
